<template>
    <div style="padding: 12px; box-sizing: border-box;">
        <el-dialog v-model="dialogVisible" :title="formData?.id ? '关联账单修改' : '关联账单新增'" width="70%">
            <el-form class="sform" style="height:550px;overflow-y:scroll;position:relative" :inline="true"
                :model="formData">

                <el-form-item label="关联日期">
                    <el-date-picker type="datetime" style="width: 430px;" format="YYYY年MM月DD日 HH时mm分ss秒"
                        v-model="formData.createTime" placeholder="关联日期" clearable />

                </el-form-item>

                <el-form-item label="订单编码">
                    <el-input style="width: 430px;" disabled v-model="formData.code" placeholder="订单编码" clearable />
                </el-form-item>
                <el-form-item label="订单备注">
                    <el-input style="width: 960px;" :rows="4" type="textarea" v-model="formData.remark" placeholder="备注"
                        clearable />
                </el-form-item>

                <div style="margin: 20px;font-size: 24px;font-weight: bolder;">客户订单信息</div>
                <el-transfer :titles="['全部订单', '绑定订单']" v-model="formData.uid" filterable :filter-method="filterMethod"
                    filter-placeholder="请选择要关联的客户订单" :data="udatalist" />
                <div style="margin: 20px;font-size: 24px;font-weight: bolder;">供商订单信息</div>
                <el-transfer :titles="['全部订单', '绑定订单']" style="width: 100%;" v-model="formData.sid" filterable
                    :filter-method="filterMethod" filter-placeholder="请选择要关联的供应商订单" :data="sdatalist" />

            </el-form>

            <template #footer>
                <div>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="onSubmit" type="primary">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <sDialog ref="sdialog" :content="scontent" :style="{ width: scontent ? '600px' : '80%' }"
            :confirmFunction="confirmFunction"> <template v-slot:content>
                <div v-if="previewType == 'mlinfo'"
                    style="display: flex; flex-direction: column; align-items: center; width: 100%;margin-top: 20px;">
                    <div
                        style="display: flex;flex-direction:column;width: 450px;align-items: center;margin-bottom: 10px;">
                        <div
                            style="display: flex;justify-content: space-between;width: 100%;margin-top: 20px;font-size: 20px;">
                            毛利润: {{ mlinfo.ml }} 元
                        </div>
 
                        <div
                            style="display: flex;justify-content: space-between;width: 100%;margin-top: 20px;font-size: 20px;">
                            毛利率: {{ mlinfo.mll }} %
                        </div>

                        <div
                            style="display: flex;align-items:center; width: 100%;margin-top: 20px;">
                            <div style="font-size: 20px;width: 100px;">提成比例:</div>  <el-input style="width:100px;" @input="handlejsr" type="number"  v-model="srinfo.yjl" placeholder="个人提成"
                            clearable />%
                        </div>
                        <el-divider></el-divider>
                        <div
                            style="display: flex;align-items:center; width: 100%;margin-top: 20px;">
                            <div style="font-size: 20px;width: 100px;">税率:</div>  <el-input style="width:100px;" @input="handlejsr" type="number"  v-model="srinfo.sl" placeholder="个人税率"
                            clearable />%
                        </div>
              
                        <div
                            style="display: flex;align-items: center; width: 100%;margin-top: 20px;">
                            <div style="font-size: 20px;width: 100px;">销售费用:</div>  <el-input @input="handlejsr" style="width: 100px;" type="number" v-model="srinfo.cb" placeholder="销售费用"
                        clearable />元
                        </div>
               
                        <el-divider></el-divider>
                        <div
                            style="display: flex;align-items:center; width: 100%;margin-top: 20px;font-size: 20px;">
                            <div style="font-size: 20px;width: 100px;">提成收入:</div>  <div>{{srinfo.jsr}}元</div> 
                        </div>
                    </div>
                </div>
            </template>
        </sDialog>
        <el-card style="width: 100%;">

            <!-- <el-form :inline="true" style="margin-top: 20px;" :model="{}">
     

                <el-form-item label="订单日期">
                    <el-date-picker format="YYYY年MM月DD日" style="width: 500px;" v-model="queryParams.ShippingDate"
                        type="daterange" range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期" />

                </el-form-item>


                <el-form-item>
                    <el-button @click="handleQuery" type="primary">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form> -->
        </el-card>


        <el-card style="width: 100%;margin-top:10px">
            <template #header>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <div> <span style="margin-right: 10px;">关联账单列表</span>
                        <span style="color:#aaaaaa;font-size: 13px;">共计{{ listInfo.total }}条账单</span>
                    </div>

                    <el-space>
                        <!-- v-hasPermiss="rolepathName('sum')" -->
                        <!-- <el-button @click="handleCalculate()" type="success">计算总额</el-button> -->
                        <el-button @click="handleForm()" v-hasPermiss="rolepathName('add')" type="primary">新增</el-button>
                        <!-- <el-button @click="IdataExport()" type="warning">导出</el-button> -->
                    </el-space>

                </div>
            </template>
            <el-table :data="listInfo.list" border default-expand-all height="550"
                style="width: 100%;  margin-bottom: 20px">


                <el-table-column align="center" prop="code" width="200px" label="关联订单编码" />




                <!-- 
                <el-table-column align="center" prop="product" width="200px" label="产品信息">
                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <el-space direction="vertical">
                                    <div v-for="(e, i) in scope.row.product"><el-tag>产品{{ i + 1 }}:{{ e?.pid?.name
                                    }}规格:{{
                                                e?.specification && e?.specification[0]
                                            }}
                                            单价:￥{{
                                                e?.price && e?.price[0]
                                            }} 数量:{{ e.number
                                            }}{{ e?.pid?.unit }}</el-tag></div>
                                </el-space>
                            </template>
                            <el-space style="cursor:pointer" direction="vertical">
                                <div>{{[...new Set(scope.row.product.map((e: any) => e?.pid?.name))].toString()}}
                                </div>

                            </el-space>
                        </el-tooltip>
                    </template>
                </el-table-column> -->
                <el-table-column align="center" prop="uid" width="260px" label="客户订单">
                    <template #default="scope">



                      
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <div v-for="e in scope.row.uid" @click="handleCopy(e.code, '客户物料编码')" class="gname" style="">{{
                            e.name }}[{{ e.code }}] </div>
                            </template>

                            <span style="cursor: pointer;"> 
                                {{ scope.row.uid.map((e:any)=>e.name).toString().length>8?scope.row.uid.map((e:any)=>e.name).toString().substr(0,
                                8) + '...' : scope.row.uid.map((e:any)=>e.name).toString() }}({{ scope.row.uid.length }})
                            </span>
                        </el-tooltip>
    



            
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="sid" width="260px" label="供应商订单">

                    <template #default="scope">





                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <div v-for="e in scope.row.sid" @click="handleCopy(e.code, '供应商订单编码')" class="gname" style="">{{
                            e.supplierName }}[{{ e.supplierCode }}] </div>
                            </template>

                            <span style="cursor: pointer;"> 
                                {{ scope.row.sid.map((e:any)=>e.supplierName).toString().length>8?scope.row.sid.map((e:any)=>e.supplierName).toString().substr(0,
                                8) + '...' : scope.row.sid.map((e:any)=>e.supplierName).toString() }}({{ scope.row.uid.length }})
                            </span>
                        </el-tooltip>

                  
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="remark" width="360px" label="订单备注" />
                <el-table-column align="center" prop="createTime" width="120px" label="创建时间">
                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <span> {{ scope.row.createTime }}</span>
                            </template>
                            <span style="cursor: pointer;"> {{
                                (scope.row.createTime.split('') && scope.row.createTime.split(' ')[0]
                                ) }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>



                <el-table-column align="center" fixed="right" min-width="250px" label="操作">
                    <template #default="scope">
                        <el-space wrap>
                            <el-button size="small" @click="handleForm(scope.row._id)" v-hasPermiss="rolepathName('put')" type="primary">编辑</el-button>
                            <el-button size="small" @click="deletem(scope.row._id)" v-hasPermiss="rolepathName('delete')" type="danger">删除</el-button>
                            <el-button size="small" @click="cumulate(scope.row)" v-hasPermiss="rolepathName('sum')" type="success">计算</el-button>
                        </el-space>

                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div style="display: flex;justify-content: center;">
                    <el-pagination :page-sizes="[5, 10, 15, 20]" layout="sizes, prev, pager, next" @size-change="sc"
                        @current-change="cc" v-model:current-page="listInfo.cpage" v-model:page-size="listInfo.pageSize"
                        background :total="listInfo.total" />
                </div>
            </template>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue"
import { resetAble } from "../../composable/reset"
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { getBillList } from "../../api/bill";
import { getSupBillList } from "../../api/supplier";
import { getOrderRandomCode, addOrder, putOrder, delOrder, getOrder, orderlList } from "../../api/order"
import { handleCopy } from "../../utils/usecopy"
import { rolepathName } from "../../composable/dealname";

const filterMethod = (query: any, item: any) => {
    return item.label.toLowerCase().includes(query.toLowerCase())
}


const udatalist = ref<any>([])

const sdatalist = ref<any>([])


const sc = (e: any) => {

    listInfo.value.pageSize = e
    init()
}
const cc = (e: any) => {

    listInfo.value.cpage = e
    init()
}
const {data:srinfo,reset:srreset}=resetAble({
    cb:0,
    yjl:5,
    jsr:0,
    sl:15
}) as any
// const {} = srinfo=ref({})

// const cb=ref<any>(0)
// const yjl=ref<any>(100)
// const jsr=ref<any>(0)


const handlejsr=()=>{
    srinfo.value.jsr=Number( ((((mlinfo.value.ml-srinfo.value.cb)*(1-srinfo.value.sl/100)))*srinfo.value.yjl/100)).toFixed(2) 
}


// const totalsum = ref<any>({})

// const handleCalculate = async () => {
//     await getTotalAmount({
//         data: queryParams.value,
//         params: {
//             currentPage: listInfo.value.cpage,
//             pageSize: listInfo.value.pageSize
//         }
//     }).then(res => {

//         totalsum.value = res.data
//         previewType.value = 'suminfo'
//         scontent.value = '总额信息'
//         proxy.$refs.sdialog.showCenterDialog = true
//     })
// }





// const handleQuery = () => {

//     init().then(() => {
//         ElMessage({
//             message: '查询成功',
//             grouping: true,
//             type: 'success',
//         })
//     })
// }
// const handleReset = () => {
//     // resetQueryParams()
//     // init().then(() => {
//     //     ElMessage({
//     //         message: '重置成功',
//     //         grouping: true,
//     //         type: 'success',
//     //     })
//     // })
// }


const dialogVisible = ref(false)
const { proxy } = getCurrentInstance() as any
const { data: formData, reset } = resetAble({
    uid: [],
    sid: [],
    code: "",
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    remark: ""
}) as any





const handleForm = async (id?: string) => {

    if (id) {
        formData.value.id = id
        await getOrder({ id }).then((res: any) => {
            formData.value = res.data
            formData.value.id = formData.value._id
            dialogVisible.value = true
        })


    } else {
        IgetRandomCode().then(() => {

            dialogVisible.value = true
        })
        reset()
    }

}

const confirmFunction = () => {
    if (formData.value.id) {
        delOrder({ id: formData.value.id }).then((res: any) => {
            if (res) {
                init().then(() => {
                    ElMessage({
                        message: '操作成功',
                        grouping: true,
                        type: 'success',
                    })
                })
            }
        })
    }

}
const scontent = ref<any>(null)
const deletem = async (id: string) => {
    formData.value.id = id
    scontent.value = '确定要删除该账单吗？'
    proxy.$refs.sdialog.showCenterDialog = true
}
const mlinfo = ref<any>({})
const previewType = ref<any>(null)
const cumulate = (item: any) => {

    let totalsup = item.sid.reduce((acc: any, bill: any) => acc + (bill.supplierAmount || 0), 0).toFixed(2)
    let totaluser = item.uid.reduce((acc: any, bill: any) => acc + (bill.amount || 0), 0).toFixed(2)




    previewType.value = 'mlinfo'
    scontent.value = '毛利信息'
    mlinfo.value.ml = (totaluser - totalsup).toFixed(2)
    mlinfo.value.mll = Number(mlinfo.value.ml / totaluser * 100).toFixed(2)
    srreset()
    handlejsr()

    proxy.$refs.sdialog.showCenterDialog = true

}
const onSubmit = async () => {
    formData.value.createTime = +dayjs(formData.value.supplierDate).valueOf()


    if (formData.value.id) {
        let res = await putOrder(formData.value) as any
        if (res && res.code == 200) {
            init().then(() => {
                ElMessage({
                    message: '操作成功',
                    grouping: true,
                    type: 'success',
                })
            })
            dialogVisible.value = false
        }
    } else {
        let res = await addOrder(formData.value) as any
        if (res && res.code == 200) {
            init().then(() => {
                ElMessage({
                    message: '操作成功',
                    grouping: true,
                    type: 'success',
                })
            })
            dialogVisible.value = false
        }
    }

}
// const IgetProduct = async () => {
//     let res = await getProductList({
//         data: {
//             isAll: true
//         }
//     } as any)
//     if (res) {
//         productList.value = res.data.map((e: any) => {
//             return {
//                 value: e._id,
//                 label: e.name,
//                 price: e.price,
//                 specification: e.specification,
//                 unit: e.unit,

//             }
//         })
//     }
// }
// IgetProduct()
const listInfo = ref({
    list: [],
    total: 0,
    cpage: 1,
    pageSize: 5
})




const IgetSupBillList = () => {
    return new Promise<void>((resolve, reject) => {
        getSupBillList({
            data: {},
            params: {
                currentPage: listInfo.value.cpage,
                pageSize: listInfo.value.pageSize,
            }
        }

        ).then((res) => {
            sdatalist.value = res.data.list.map((e: any) => {
                return {
                    label: `${e.supplierName}(${e.supplierCode})`,
                    key: e._id
                }
            })
            resolve()
        }).catch(err => {
            reject(err)
        })
    })
}



const IgetBillList = () => {
    return new Promise<void>((resolve, reject) => {
        getBillList({
            data: {},
            params: {
                currentPage: listInfo.value.cpage,
                pageSize: listInfo.value.pageSize,
                isAll: true
            }
        }

        ).then((res) => {
            if (res) {
                udatalist.value = res.data.list.map(e => {
                    return {
                        label: `${e.name}(${e.code})`,
                        key: e._id
                    }
                })
            }
            resolve()
        }).catch(err => {
            reject(err)
        })
    })
}
const init = () => {
    return new Promise<void>(async (resolve, reject) => {
        IgetSupBillList()
        IgetBillList()
        await orderlList({
            data: {},
            params: {
                currentPage: listInfo.value.cpage,
                pageSize: listInfo.value.pageSize
            }
        }).then((res: any) => {
            listInfo.value.list = res.data.list
            listInfo.value.total = res.data.total
            resolve()
        }).catch(() => {
            reject()
        })
    })
}

const IgetRandomCode = () => {
    return new Promise<void>(async (resolve, reject) => {
        await getOrderRandomCode().then((res) => {
            if (res) {
                formData.value.code = res.data
                resolve()
            }
        }).catch(() => {
            reject()
        })
    })

}


init()
</script>
<style lang="scss" scoped>
:deep(.el-icon) {
    font-style: normal;
    font-weight: bolder;
}

.gname {
    cursor: pointer;

    &:hover {
        color: #409eff;
    }
}

:deep(.el-transfer-panel) {
    width: 40%;
}
</style>